const {
  mysql
} = require('../qcloud')

module.exports = async (ctx) => {
  let {
    openId
  } = ctx.request.query;

  function formatTime(time) {
    var dt = new Date(time);
    return `${dt.getFullYear()}-${(dt.getMonth() + 1).toString().padStart(2, 0)}-${dt.getDate().toString().padStart(2, 0)} ${dt.getHours().toString().padStart(2, 0)}:${dt.getMinutes().toString().padStart(2, 0)}:${dt.getSeconds().toString().padStart(2, 0)}`
  }
  let hongbaoList = await mysql('redPacket').select('*').where('sharer_id', openId).limit(30)
  //   总奖励
  let sum = await mysql('redPacket').sum('award').where('sharer_id', openId);
  //   已提现的金额
  let everGet = await mysql('cSessionInfo').select('ever_get').where('open_id', openId);
  ctx.state.data = {
    list: hongbaoList.map(val => {
      const info = JSON.parse(val.friend_info);
      val.create_time = formatTime(val.create_time)
      delete val.friend_id;
      delete val.friend_info;
      delete val.sharer_id;
      delete val.xh;
      return Object.assign({}, val, {
        userInfo: {
          nickName: info.nickName,
          avatarUrl: info.avatarUrl
        }
      })
    }),
    everGet: Number(everGet[0].ever_get).toFixed(0),
    sum: Number(Object.values(sum[0])[0])
  }
};
